package com.borun.dictionary;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.borun.bean.Base;
import com.borun.dao.BaseDao;

public class UpdateBase extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	private BaseDao dao = new BaseDao();
	private JLabel lblBaseName;
	private JTextField txtBaseName, txtBaseId;
	private JButton btnUpdate, btnCancel;

	public UpdateBase(String baseid) {

		this.setLayout(null);

		lblBaseName = new JLabel("词库名称：");
		lblBaseName.setBounds(30, 40, 100, 30);

		txtBaseId = new JTextField();
		txtBaseId.setText(baseid);
		txtBaseId.setBounds(100, 40, 160, 30);
		txtBaseId.setVisible(false);

		txtBaseName = new JTextField();
		txtBaseName.setBounds(100, 40, 160, 30);

		btnUpdate = new JButton("更新");
		btnUpdate.addActionListener(this);
		btnUpdate.setBounds(50, 120, 80, 30);

		btnCancel = new JButton("取消");
		btnCancel.addActionListener(this);
		btnCancel.setBounds(160, 120, 80, 30);

		this.add(lblBaseName);
		this.add(txtBaseName);
		this.add(btnUpdate);
		this.add(btnCancel);

		try {
			Base b = dao.getBase(Integer.valueOf(baseid));
			txtBaseName.setText(b.getBasename());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		this.setSize(300, 200);
		this.setLocationRelativeTo(null); // 设置窗口相对于指定组件的位置
		this.setResizable(false); // 禁止改变窗体大小
		//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	// public static void main(String[] args) {
	// new UpdateBase(1);
	// }

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnUpdate) {
			String baseid = txtBaseId.getText();
			String basename = txtBaseName.getText();
			if ("".equals(basename) || basename.trim().isEmpty()) {
				JOptionPane.showMessageDialog(null, "请正确填写词库名称！");
				return;
			}
			Base base = new Base(Integer.valueOf(baseid), basename);
			try {
				if (dao.updateBase(base)) {
					JOptionPane.showMessageDialog(null, "更新成功！");
					this.setVisible(false);
				} else {
					JOptionPane.showMessageDialog(null, "系统异常，更新失败！");
				}
			} catch (HeadlessException e1) {
				e1.printStackTrace();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} else if (e.getSource() == btnCancel) {
			this.setVisible(false);
		}
	}

}
